<?php

namespace app\support\concerns;

trait JsonSave
{
    /**
     * @param string $filepath
     * @param string $data
     * @return void
     */
    protected function saveJson(string $filepath, string $data)
    {
        file_put_contents($filepath, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }

    /**
     * @param string $subFilepath
     * @param string $data
     * @return void
     */
    protected function saveJsonToPublic(string $subFilepath, string $data)
    {
        $this->saveJson(public_path($subFilepath), $data);
    }

    /**
     * @param string $filepath
     * @return mixed|null
     */
    protected function readJson(string $filepath)
    {
        if (!file_exists($filepath)) {
            return null;
        }

        return json_decode(file_get_contents($filepath), true);
    }

    /**
     * @param string $subFilepath
     * @return mixed|null
     */
    protected function readJsonToPublic(string $subFilepath)
    {
        return $this->readJson(public_path($subFilepath));
    }
}
